﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Framework.Common.Sql;
using System.Text;
using System.Data.SqlClient;
namespace Diaocha.Controllers
{
    public class VoteController : Controller
    {
        public static int Version = Framework.Common.Configs.SystemConfig.GetInt("version");
        // GET: /Vote/
        [HttpGet]
        public ActionResult Employee()
        {
            if (Session["userid"] == null)
            {
                JsHelper.AlertAndRedirect("请先登录,或登陆超时", "/");
                return null;
            }
            if (Session["role"].ToString() == "manager")
            {
                JsHelper.AlertAndRedirect("即将进入自评问卷调查", "/vote/manager");
                return null;
            }
            if (CheckExists(Session["userid"].ToString(), 1, Version))//如果填过了
            {
                JsHelper.AlertAndRedirect("您已经答过题了", "/");
                return null;
            }
            string sql = "SELECT top 1 supname  FROM [dbo].[Staff]  WHERE WWID = @userid";
            var obj = SqlHelper.ExecuteScalar(
                HomeController.connectionString,
                CommandType.Text,
                sql,
                new SqlParameter("@userid", Session["userid"].ToString())
            );
            ViewBag.SupName = obj;
            ViewBag.Q = dsQuestion.AsEnumerable().Where(i => i.Field<int>("paperid") == 1);
            return View();
        }

        [HttpPost]
        public ActionResult Employee(FormCollection form)
        {
            if (Session["userid"] == null)
            {
                JsHelper.AlertAndRedirect("请先登录,或登陆超时", "/");
                return null;
            }
            return GetResult(1);
        }

        [HttpGet]
        public ActionResult Manager()
        {
            if (Session["userid"] == null)
            {
                JsHelper.AlertAndRedirect("请先登录,或登陆超时", "/");
                return null;
            }
            if (Session["role"].ToString() == "employee")
            {
                JsHelper.AlertAndRedirect("即将进入下属问卷调查", "/vote/employee");
                return null;
            }
            if (CheckExists(Session["userid"].ToString(), 2, Version))//如果填过了
            {
                JsHelper.AlertAndRedirect("您已经答过题了", "/");
                return null;
            }
            ViewBag.Q = dsQuestion.AsEnumerable().Where(i => i.Field<int>("paperid") == 2);
            return View();
        }

        [HttpPost]
        public ActionResult Manager(FormCollection form)
        {
            if (Session["userid"] == null)
            {
                JsHelper.AlertAndRedirect("请先登录,或登陆超时", "/");
                return null;
            }
            return GetResult(2);
        }


        public ActionResult Choice()
        {
            string sql = "SELECT top 1 supname,namecn  FROM [dbo].[Staff]  WHERE WWID = @userid";
            var ds = SqlHelper.ExecuteDataset(HomeController.connectionString, CommandType.Text, sql, new SqlParameter("@userid", Session["userid"].ToString()));
            ViewBag.Info = ds;
            ViewBag.XiaShu = CheckExists(Session["userid"].ToString(), 1, Version);
            ViewBag.ZiPing = CheckExists(Session["userid"].ToString(), 2, Version);
            return View();
        }


        bool CheckExists(string userid, int paperid, int version)
        {
            string sql = "SELECT COUNT(*)  FROM [Diaocha].[dbo].[StaffScore]  WHERE userid=@userid AND paperid=@paperid AND version=@version";
            var obj = SqlHelper.ExecuteScalar(HomeController.connectionString, CommandType.Text, sql,
                                       new SqlParameter("@userid", Session["userid"].ToString()),
                                       new SqlParameter("@paperid", paperid),
                                       new SqlParameter("@version", version));
            return Convert.ToInt32(obj) > 0;
        }

        private ActionResult GetResult(int paperid)
        {
            var keys = dsQuestion.AsEnumerable().Where(i => i.Field<int>("paperid") == paperid);

            using (SqlConnection conn = new SqlConnection(HomeController.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        foreach (var key in keys)
                        {
                            if (key["qtype"].ToString() == "radio")
                            {
                                int value = RequestExtention.GetInt("q" + key["questionid"], -1);
                                if (value >= 0)
                                {
                                    string sql = "insert into [StaffScoreCheckDetail] values(@userid," + paperid + ",@questionid,@answerid,1)";
                                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sql,
                                        new SqlParameter("@userid", Session["userid"].ToString()),
                                        new SqlParameter("@questionid", Convert.ToInt32(key["questionid"])),
                                        new SqlParameter("@answerid", value));
                                }
                            }
                            else if (key["qtype"].ToString() == "mradio")
                            {
                                for (int i = 0; i < 20; i++)
                                {
                                    int value = RequestExtention.GetInt("q" + key["questionid"] + "_" + i, -1);
                                    if (value >= 0)
                                    {
                                        string sql = "insert into [StaffScoreCheckDetail] values(@userid," + paperid + ",@questionid,@answerid,1)";
                                        SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sql,
                                            new SqlParameter("@userid", Session["userid"].ToString()),
                                            new SqlParameter("@questionid", Convert.ToInt32(key["questionid"])),
                                            new SqlParameter("@answerid", value));
                                    }
                                }
                            }
                            else if (key["qtype"].ToString() == "input")
                            {
                                string value = RequestExtention.GetString("q" + key["questionid"]);
                                if (!string.IsNullOrEmpty(value))
                                {
                                    string sql = "insert into [StaffScoreInputDetail] values(@userid," + paperid + ",@questionid,@answer,1)";
                                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sql,
                                        new SqlParameter("@userid", Session["userid"].ToString()),
                                        new SqlParameter("@questionid", Convert.ToInt32(key["questionid"])),
                                        new SqlParameter("@answer", value));
                                }
                            }
                            else if (key["qtype"].ToString() == "check")
                            {
                                string values = RequestExtention.GetString("q" + key["questionid"]);
                                if (!string.IsNullOrEmpty(values))
                                {
                                    string sql = "insert into [StaffScoreCheckDetail] values(@userid," + paperid + ",@questionid,@answerid,1)";
                                    foreach (var aid in values.Split(','))
                                    {
                                        SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sql,
                                            new SqlParameter("@userid", Session["userid"].ToString()),
                                            new SqlParameter("@questionid", Convert.ToInt32(key["questionid"])),
                                            new SqlParameter("@answerid", Convert.ToInt32(aid)));
                                    }
                                }
                            }
                        }
                        SqlHelper.ExecuteNonQuery(trans, CommandType.Text, "insert into [StaffScore] values(@userid," + paperid + ",0,1,getdate())", new SqlParameter("@userid", Session["userid"].ToString()));
                        trans.Commit();
                        JsHelper.AlertAndRedirect("感谢您的参与", "/");
                        return null;
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        Framework.Common.LogHelper.Error("保存出错", ex);
                        JsHelper.AlertAndRedirect("保存出错", "/");
                        return null;
                    }
                }
            }
        }

        public static IList<DataRow> GetAnswer(int questionID)
        {
            return dsAnswer.AsEnumerable().Where(i => i.Field<int>("questionid") == questionID).ToList();
        }

        public static DataSet dsQuestion;
        public static DataSet dsAnswer;

        static VoteController()
        {
            string sql =
@"  SELECT  [questionid] ,
            [paperid] ,
            [qtitle] ,
            [qtype] ,
            [qorder]
    FROM    [Diaocha].[dbo].[Question]
    order by paperid,qorder";

            dsQuestion = SqlHelper.ExecuteDataset(HomeController.connectionString, CommandType.Text, sql);




            sql =
@"  SELECT [answerid]
          ,[questionid]
          ,[atitle]
          ,[xtitle]
          ,[ytitle]
          ,[aorder]
          ,[score]
      FROM [Diaocha].[dbo].[Answer]
      ORDER BY questionid,aorder";

            dsAnswer = SqlHelper.ExecuteDataset(HomeController.connectionString, CommandType.Text, sql);
        }
    }
}
